<template>
  <!-- EXCEL导入按钮 -->
  <a-upload
    :disabled="loading"
    accept=".xls,.xlsx"
    :show-upload-list="false"
    name="file"
    :multiple="multiple"
    v-bind="$attrs"
    :before-upload="exportData"
    v-on="$listeners"
  >
    <!-- 导入按钮 -->
    <a-button
      v-if="!custom"
      :loading="loading"
      type="primary"
      v-bind="$attrs"
      :disabled="disabled"
    >
      {{
        buttonText
      }}
    </a-button>
    <!-- 插槽 -->
    <slot v-else />
  </a-upload>
</template>

<script>
// 该组件使用了xlsx第三方库(sheetJS/JS-XLSX)
import XLSX from 'xlsx'

export default {
  name: 'ExcelImportButton',
  props: {
    // 导入按钮文本
    buttonText: {
      type: String,
      default: () => '批量导入'
    },
    // 自定义上传容器
    custom: {
      type: Boolean,
      default: () => false
    },
    // 禁用按钮
    disabled: {
      type: Boolean,
      default: () => false
    },
    // 需要读取excel的sheet的索引值（excel底部tab索引）
    sheetIndex: {
      type: [String, Number],
      default: () => 0
    },
    // 读取全部
    readAll: {
      type: Boolean,
      default: () => false
    },
    // 需要读取excel起始行
    rowIndex: {
      type: [Number, String],
      default: () => 0
    },
    // 导出配置参数
    sheetOptions: Object,
    // 按钮加载控件
    loading: {
      type: Boolean,
      default: () => false
    },
    // 多选
    multiple: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  methods: {
    /**
     * 将excel生成数组
     */
    exportData(file) {
      console.log('file',file)
      this.$emit('update:loading',true)
      // 拿取文件对象，注：不同框架获取到的对象可能不同，传统upload拿到的对象应该是e.target.file
      let f = file
      let binary = ''
      let wb
      var outdata = []
      let reader = new FileReader()
      reader.onload = (e) => {
        // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
        let bytes = new Uint8Array(reader.result)
        let length = bytes.byteLength
        for (var i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i])
        }
        wb = XLSX.read(binary, {
          type: 'binary',
          cellDates: true
        })
        //最后生成的数组
        if (this.readAll) {
          // 读取全部
          for (let index in wb.Sheets) {
            let item = wb.Sheets[index]
            let lastIndex = item['!ref']?.split(':')?.[1]
            outdata.push(
              XLSX.utils.sheet_to_json(
                item,
                Object.assign({}, { range: `A${this.rowIndex}:${lastIndex}` }, this.sheetOptions)
              )
            )
          }
        } else {
          // 读取指定
          // 解决读取日期少一天
          let data = wb.Sheets[wb.SheetNames[this.sheetIndex]]
          for (let item in data) {
            for (let childItem in data[item]) {
              if (data[item][childItem] === 'd') {
                let dateTime = data[item].v
                dateTime = dateTime.setDate(dateTime.getDate() + 1)
                data[item].v = new Date(dateTime)
              }
            }
          }

          outdata = XLSX.utils.sheet_to_json(data)
        }
        if (this.$listeners['handleSubmit']) {
          this.$emit('handleSubmit', outdata)
        }
      }
      reader.readAsArrayBuffer(f)
      return false
    }
  }
}
</script>
